package com.szlanyou.thirdsdk.retrofit.loading.helper;

import android.app.Activity;
import android.util.Log;

import com.szlanyou.thirdsdk.retrofit.client.HttpClient;
import com.szlanyou.thirdsdk.retrofit.loading.INetLoadingManage;
import com.szlanyou.thirdsdk.retrofit.loading.NetLoadingStateAction;
import com.szlanyou.thirdsdk.retrofit.util.MyLogUtil;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author 陈章
 * create at 2021/7/15 10:12
 * desc:
 * 辅助开发者去快速创建Dialog形式的Loading，每一个Activity绑定一个Loading实例
 *
 * 备注：不只是适用于网络请求{@link HttpClient}类，也适用于任何其它类似通信形式。
 */
public abstract class ActivityDialogLoadingHelper {
    private static final String TAG = "DialogLoadingHelper";
    private NetLoadingStateAction loadingAction;
    private Set<INetLoadingManage> clients;

    public ActivityDialogLoadingHelper() {
        clients = new HashSet<>();
    }

    /**
     * 注册需要Loading实例的对象
     * @param netLoadingManage
     */
    public void registerHttpClient(INetLoadingManage netLoadingManage){
        if(clients.contains(netLoadingManage)){
            clients.remove(netLoadingManage);
        }
        clients.add(netLoadingManage);
    }

    public void onCreate(Activity activity){
        loadingAction = onCreateLoadingAction(activity);
        MyLogUtil.d(TAG,"create loading action on activity " + activity);
    }

    public void onStart(Activity activity){
        rejectLoadingForClients(activity);
    }

    public void onDestroy(Activity activity){
        unRejectLoadingForClients(activity);
    }

    /**
     * 注入Loading实例到使用端
     */
    private void rejectLoadingForClients(Activity activity) {
        hideExistingLoading();
        for (INetLoadingManage item : clients){
            MyLogUtil.d(TAG,"reject loadingAction  + " + loadingAction + "for client " + item);
            item.setLoadingAction(loadingAction);
        }
    }

    /**
     * 关闭已经存在的Loading
     */
    private void hideExistingLoading(){
        if(loadingAction != null && loadingAction.isShowing()){
            loadingAction.hideLoading();
        }
    }

    /**
     * 关闭未关闭的Loading并删除Loading实例
     */
    private void unRejectLoadingForClients(Activity activity) {
        //仅关闭当前activity上的dialog
        boolean hide = loadingAction != null && loadingAction.isShowing();
        if(hide){
            MyLogUtil.d(TAG,"hideLoading on " + activity + " onDestroy");
            loadingAction.hideLoading();
            loadingAction = null;
        }

        //要去掉引用，否则会有内存泄漏。
        for (INetLoadingManage item : clients){
            MyLogUtil.d(TAG,"releaseLoading for client " + item);
            item.releaseLoadingAction(activity);
        }
    }

    /**
     * 创建Loading框实例
     * @param activity  dialog所在的activity
     * @return
     */
    public abstract NetLoadingStateAction onCreateLoadingAction(Activity activity);
}
